package algorithm;

import java.util.Map;
import java.util.TreeMap;

public class TreeMapDemo {
    /*介绍TreeMap:headMap函数用法*/
    public static Map<Integer, String> useHeadMap(){
        System.out.println("Use headMap()");
        TreeMap<Integer, String> students = new TreeMap<>();
        students.put(80, "Alice");
        students.put(85,"Bob");
        students.put(90, "Charlie");
        students.put(95, "David");

        // 获取小于90的学生视图（不包括90）
        Map<Integer, String> lessThan90Students = students.headMap(90);
        for(Integer score : lessThan90Students.keySet()){
            System.out.println("Score: " + score + ", Name: " + lessThan90Students.get(score));
        }
        return lessThan90Students;
    }
    /*介绍TreeMap:subMap函数用法*/
    public static Map<Integer, String> useSubMap(){
        System.out.println("Use subMap()");
        TreeMap<Integer, String> students = new TreeMap<>();
        students.put(80, "Alice");
        students.put(85, "Bob");
        students.put(90, "Charlie");
        students.put(95, "David");

        // 获取成绩在85（包括）到90（不包括）之间的学生视图
        Map<Integer, String> selectedStudents = students.subMap(85, 90);
        for (Integer score : selectedStudents.keySet()){
            System.out.println("Score: " + score + ", Name: " + selectedStudents.get(score));
        }
        return selectedStudents;
    }
    /*介绍TreeMap:tailMap函数用法*/
    public static Map<Integer, String> useTailMap(){
        System.out.println("Use tailMap()");
        TreeMap<Integer, String> students = new TreeMap<>();
        students.put(80, "Alice");
        students.put(85, "Bob");
        students.put(90, "Charlie");
        students.put(95, "David");
        students.put(76, "Tom");

        // 获取成绩大于等于85的学生(包含85)
        Map<Integer, String> moreThan90Students = students.tailMap(85);
        for (Integer score : moreThan90Students.keySet()){
            System.out.println("Score: " + score + ", Name: " + moreThan90Students.get(score));
        }
        return moreThan90Students;
    }

    public static void main(String[] args) {
        useHeadMap();
        useSubMap();
        useTailMap();
    }
}
